package com.wust.footprint;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;






import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;




import com.wust.R;

import com.wust.diary.Diary;
import com.wust.diary.DiaryDao;
import com.wust.http.HttpUtil;
import com.wust.menu.FirstGroupTab;
import com.wust.menu.MainActivity;
import com.wust.menu.PullToRefreshListView;
import com.wust.menu.PullToRefreshListView.OnRefreshListener;
import com.wust.util.ConstDefine;
import com.wust.util.JsonUtil;
import com.wust.util.SqltimeToTime;

public class diaryList extends ListActivity {
	private ListView listview=null;
	private ArrayList<HashMap<String, Object>> listItems;
	private DiaryDao diaryDao;
	private Diary diary;
	private String user_name;
	private String diary_time;
	private ImageButton adddiary=null;
	private SqltimeToTime timeTransfer;
	private int month;
	private int year;
	private NewsAdapter adapter;
	private int lastItem;
	private List diarylist;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary_list);
		Intent intent=getIntent();
		SharedPreferences preferences = getSharedPreferences("userinfo",0);
		user_name=preferences.getString("user_name", "");
		diaryDao=new DiaryDao(this);	
		timeTransfer=new SqltimeToTime();
		month=timeTransfer.dateToSqlTime(new Date()).getMonth();
		year=timeTransfer.dateToSqlTime(new Date()).getYear();
		adddiary=(ImageButton)findViewById(R.id.img_add_record);
		adddiary.setOnClickListener(new addDiaryListener());
		registerForContextMenu(this.getListView());
		
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		System.out.println("start");
		super.onStart();
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		System.out.println("stop");
		super.onStop();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("destory");
		super.onDestroy();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		 ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
	            public void onRefresh() {
	            	/**加载数据，刷新ListView*/
	                new GetDataTask().execute();
	            }
	        });
	        
	        getListView().setOnScrollListener(new OnScrollListener() {
				
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					System.out.println("adapter:"+adapter.getCount());
					if (lastItem == adapter.getCount() - 1 && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
						addMoreData();
					}
				}
				
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
				//	Log.i(PullToRefreshActivity.class.getCanonicalName(), firstVisibleItem+"firstVisibleItem");
					//Log.i(PullToRefreshActivity.class.getCanonicalName(), visibleItemCount+"visibleItemCount");

					lastItem = firstVisibleItem - 2 + visibleItemCount;
				}
			});
	        listview=getListView();
	        ItemOnLongClick2();
	        listItems=getDiaryList();
	        adapter = new NewsAdapter();
	        setListAdapter(adapter);
		
		super.onResume();
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		ProgressDialog dialog = new ProgressDialog(this.getParent());
		
		dialog.setMessage("加载中...请稍候");
		dialog.setIndeterminate(true);
		
		dialog.setCancelable(true);
		return dialog;
	}
	private void addMoreData() {
    	showDialog(0);
    	new Thread(){
    		public void run() {
    			month=month-1;
    			if(month==0)
    			{
    				month=12;
    				year=year-1;
    			}
    			String diary_time=year+"-"+month;
    			DiaryDao diaryDao=new DiaryDao(diaryList.this);
    			diarylist=diaryDao.queryDiaryList(user_name,diary_time);
    			if(diarylist!=null)
    			{
    			for (int i=0;i<diarylist.size();i++) {
    				Diary diary = (Diary) diarylist.get(i);
    				HashMap<String ,Object> m1=new HashMap<String,Object>();
    				
    				Date time=timeTransfer.stringToDate(diary.getDiary_date(), "yyyy-MM-dd");
    				
    				timeTransfer=timeTransfer.dateToSqlTime(time);
    				m1.put("txt_diary_date_day", timeTransfer.getDay());
    			    m1.put("txt_diary_date_month", timeTransfer.getMonth());
    			    m1.put("txt_diary_date_year", timeTransfer.getYear());
    			    m1.put("txt_diary_date_weekday", timeTransfer.getDay_of_week());
    			    m1.put("txt_diary_date_time", timeTransfer.stringToDate(diary.getDiary_date(),"yyyy-MM"));
    			    m1.put("txt_diary_content", diary.getDiary_content());
    			    m1.put("txt_baby_age", diary.getDiary_title());
    			    listItems.add(m1);
    			}
    			}
    			try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                	e.printStackTrace();
                }
    			runOnUiThread(new Runnable() {
					public void run() {
						removeDialog(0);
						adapter.notifyDataSetChanged();
					}
				});
    		};
    	}.start();
    }
	@Override  
    public void onBackPressed() {   
        //把后退事件交给子Activity处理  
		Intent intent = new Intent(diaryList.this, FirstActivity.class);  
        // 把Activity转换成一个Window，然后转换成View  
        Window w = FirstGroupTab.group.getLocalActivityManager()  
                .startActivity("FirstActivity",intent);  
        View view = w.getDecorView();  
        //设置要跳转的Activity显示为本ActivityGroup的内容  
        FirstGroupTab.group.setContentView(view);  
    } 
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		
	}
	
	/*@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		menu.setHeaderTitle("Item");
		menu.add(0, 0, 0, "上传");
		menu.add(0, 1, 0, "删除");
		menu.add(0, 2, 0, "删除ALL");

		super.onCreateContextMenu(menu, v, menuInfo);
	}*/
	public void ItemOnLongClick2()
	{
		listview
		.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.add(0, 0, 0, "添加");
				menu.add(0, 1, 0, "删除");
				menu.add(0, 2, 0, "删除ALL");

			}
		});
			
		
	}
			// 长按菜单响应函数
			public boolean onContextItemSelected(MenuItem item) {

				AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();  
		//		MID = (int) info.id;// 这里的info.id对应的就是数据库中_id的值
				
				switch (item.getItemId()) {
				case 0:
					// 添加操作
					Gson gson=new Gson();
					int pos=info.position;
					System.out.println("info:"+info.position);
			    	 Diary diary=(Diary) diarylist.get(pos-1);
			    	 diary.setUser_name(user_name);
			    	 diary.setDiary_hastrans(1);
			    	 Map<String,String>map=new HashMap<String,String>();
			    	 map.put("json", gson.toJson(diary));
			    	 try {
						HttpUtil.postRequest(ConstDefine.URL+"uploadDiary.action",map);}
					 catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;

				case 1:
					// 删除操作
					 DiaryDao diaryDao=new DiaryDao(diaryList.this);
					pos=info.position;
					 diary=(Diary) diarylist.get(pos-1);
					 System.out.println("diaryid:"+diary.getDiary_id());
					 diaryDao.deleteDiary(String.valueOf(diary.getDiary_id()));
					 listview.setAdapter(buildAdapter());
					break;

				case 2:
					// 删除ALL操作
					break;

				default:
					break;
				}

				return super.onContextItemSelected(item);

			}

	
	private ArrayList<HashMap<String, Object>> getDiaryList()
	{
		listItems = new ArrayList<HashMap<String, Object>>();
		if(diary_time==null)
		{
			diary_time=timeTransfer.dateToString(new Date(), "yyyy-MM");
		}
		diarylist=diaryDao.queryDiaryList(user_name,diary_time);
		if(diarylist!=null)
		{
		for (int i=0;i<diarylist.size();i++) {
			Diary diary = (Diary) diarylist.get(i);
			HashMap<String ,Object> m1=new HashMap<String,Object>();
			
			Date time=timeTransfer.stringToDate(diary.getDiary_date(), "yyyy-MM-dd");
			
			timeTransfer=timeTransfer.dateToSqlTime(time);
			m1.put("txt_diary_date_day", timeTransfer.getDay());
		    m1.put("txt_diary_date_month", timeTransfer.getMonth());
		    m1.put("txt_diary_date_year", timeTransfer.getYear());
		    m1.put("txt_diary_date_weekday", timeTransfer.getDay_of_week());
		    m1.put("txt_diary_date_time", timeTransfer.stringToDate(diary.getDiary_date(),"yyyy-MM"));
		    m1.put("txt_diary_content", diary.getDiary_content());
		    m1.put("txt_baby_age", diary.getDiary_title());
		    listItems.add(m1);
		}
		}
		
		return listItems;
	}
	private  SimpleAdapter buildAdapter(){
		listItems = getDiaryList();    	

        //生成适配器的Item和动态数组对应的元素       
        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItems,//数据源        
            R.layout.diary_item,//ListItem的XML布局实现       
            //动态数组与ImageItem对应的子项               
            new String[] {"txt_diary_date_day", "txt_diary_date_month","txt_diary_date_year","txt_diary_date_weekday","txt_diary_date_time","txt_diary_content","txt_baby_age"},        
            //ImageItem的XML文件里面的一个ImageView,两个TextView ID       
            new int[] {R.id.txt_diary_date_day,R.id.txt_diary_date_month,R.id.txt_diary_date_year,R.id.txt_diary_date_weekday,R.id.txt_diary_date_time,R.id.txt_diary_content,R.id.txt_baby_age}       
        ); 
        return listItemAdapter;
	}
	private void buildList(){
		listview.setAdapter(buildAdapter());
	}
	private class addDiaryListener implements OnClickListener{
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent=new Intent();
			intent.setClass(diaryList.this, diaryAdd.class);
			
			startActivity(intent);
		}
	}
	 
	
	
	private class GetDataTask extends AsyncTask<Void, Void, LinkedList<HashMap<String, Object>>> {

        @Override
        protected LinkedList<HashMap<String, Object>> doInBackground(Void... params) {
        	LinkedList<HashMap<String, Object>> list = new LinkedList<HashMap<String,Object>>();
        
        	String result=null;
        	System.out.println("url");
        	Map<String,String>map=new HashMap<String,String>();
    		map.put("user_name", user_name);
        	try {
				result=HttpUtil.postRequest(ConstDefine.URL+"downloadDiary",map);
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        	//JsonUtil jsonUtil=new JsonUtil();
        	//diarylist=jsonUtil.praseJSON2PicArr(result);
        	Gson gson=new Gson();
        	Type type=new TypeToken<ArrayList<Diary>>(){}.getType();
        	diarylist=gson.fromJson(result, type);
        	System.out.println(diarylist);
        	if(diarylist!=null)
    		{
    		for (Iterator iterator = diarylist.iterator(); iterator.hasNext();) {
    			System.out.println("start diary");
    			Diary diary = (Diary) iterator.next();
    		
    			System.out.println("end diary");
    			HashMap<String ,Object> m1=new HashMap<String,Object>();
    			
    			Date time=timeTransfer.stringToDate(diary.getDiary_date(), "yyyy-MM-dd");
    			
    			timeTransfer=timeTransfer.dateToSqlTime(time);
    			m1.put("txt_diary_date_day", timeTransfer.getDay());
    		    m1.put("txt_diary_date_month", timeTransfer.getMonth());
    		    m1.put("txt_diary_date_year", timeTransfer.getYear());
    		    m1.put("txt_diary_date_weekday", timeTransfer.getDay_of_week());
    		    m1.put("txt_diary_date_time", timeTransfer.stringToDate(diary.getDiary_date(),"yyyy-MM"));
    		    m1.put("txt_diary_content", diary.getDiary_content());
    		    m1.put("txt_baby_age", diary.getDiary_title());
    		    list.add(m1);
    		    DiaryDao diaryDao=new DiaryDao(diaryList.this);
    		    diaryDao.insertDiary(diary);
    		}
    		}
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            	e.printStackTrace();
            }
            return list;
        }

        @Override
        protected void onPostExecute(LinkedList<HashMap<String, Object>> result) {
        	listItems.addAll(0, result);
            ((PullToRefreshListView) getListView()).onRefreshComplete();
            super.onPostExecute(result);
        }
    }

    public class NewsAdapter extends BaseAdapter {

		public int getCount() {
			return listItems.size() + 1;
		}

		public Object getItem(int position) {
			return listItems.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == getCount() - 1) {
				View view = LayoutInflater.from(
						getApplicationContext()).inflate(
						R.layout.listfooter_more, null);
				return view;
			}
			ViewHolder holder;
			if (convertView != null && convertView.getId() == R.id.diary_date_LinearLayout) {
				holder = (ViewHolder) convertView.getTag();
			} else {
				convertView = LayoutInflater.from(
						getApplicationContext()).inflate(
						R.layout.diary_item, null);
				holder = new ViewHolder();
				holder.date_day = (TextView) convertView.findViewById(R.id.txt_diary_date_day);
				holder.date_month = (TextView) convertView.findViewById(R.id.txt_diary_date_month);
				holder.date_year = (TextView) convertView.findViewById(R.id.txt_diary_date_year);
				holder.date_weekday = (TextView) convertView.findViewById(R.id.txt_diary_date_weekday);
				holder.date_time= (TextView) convertView.findViewById(R.id.txt_diary_date_time);
				holder.diary_content = (TextView) convertView.findViewById(R.id.txt_diary_content);
				holder.baby_age = (TextView) convertView.findViewById(R.id.txt_baby_age);
				convertView.setTag(holder);
			}
			holder.date_day.setText(listItems.get(position).get("txt_diary_date_day").toString());
			holder.date_month.setText(listItems.get(position).get("txt_diary_date_month").toString());
			holder.date_year.setText(listItems.get(position).get("txt_diary_date_year").toString());
			holder.date_weekday.setText(listItems.get(position).get("txt_diary_date_weekday").toString());
			holder.date_time.setText(listItems.get(position).get("txt_diary_date_time").toString());
			holder.diary_content.setText(listItems.get(position).get("txt_diary_content").toString());
			holder.baby_age.setText(listItems.get(position).get("txt_baby_age").toString());
			return convertView;
		}
		
	}
	
	public static class ViewHolder {
		TextView date_day;
		TextView date_month;
		TextView date_year;
		TextView  date_weekday;
		TextView date_time;
		TextView diary_content;
		TextView baby_age;
	}
}
